'use strict';

module.exports = core;
const path = require('path')
const log = require('@mzy-cli-dev/log')
const pkg = require("../package.json")
const semver = require('semver')
const colors = require('colors/safe');
const userHome = require('user-home');
const pathExists = require('path-exists').sync;
const { LOWEST_NODE_VERSION } = require('./const');
const { getNpmSemverVersion } = require('@mzy-cli-dev/get-npm-info')

let args;

async function core() {
    try{
        checkVersion();
        checkNodeVersion();
        checkRoot();
        checkUserHome();
        checkInputArgs();
        checkEnv();
        createDefaultConfig();
        log.verbose("环境变量", process.env.CLI_HOME_PATH)
        await checkGlobalUpdate()
    }catch(e) {
        log.error('cli', e.message)
    }
   
}

async function checkGlobalUpdate() {
    const currentVersion = pkg.version;
    const npmName = pkg.name;
    const lastVersion = await getNpmSemverVersion(currentVersion, npmName);
    if(semver.gt(lastVersion, currentVersion)) {
        log.warn('更新提示',  colors.yellow(`请手动更新${npmName}, 当前版本${currentVersion}, 最新版本${lastVersion}
        更新命令: npm i -g ${npmName}`))
    }
}

function createDefaultConfig() {
    const cliConfig = {
        home: userHome
    };
    if(process.env.CLI_HOME) {
        cliConfig['cliHome'] = path.join(userHome, process.env.CLI_HOME);
    }else{
        cliConfig['cliHome'] = path.join(userHome, constant.DEFAULT_CLI_HOME);
    }
    process.env.CLI_HOME_PATH  = cliConfig.cliHome;
}

function checkEnv() {
    const dotenv = require('dotenv');
    const dotenvPath = path.resolve(userHome, '.env');
    if(pathExists(dotenvPath)) {
        dotenv.config({
            path: dotenvPath
        })
    }
    log.verbose("env", process.env.CLI_HOME)
}

function checkInputArgs() {
    const minimist = require('minimist');
    args = minimist(process.argv.slice(2));
    checkArgs();
}

function checkArgs() {
    if(args.debug) {
        process.env.LOG_LEVEL = "verbose";
    }else{
        process.env.LOG_LEVEL = "info";
    }
    log.level = process.env.LOG_LEVEL
}

/**
 * 检查当前主目录是否存在
 */
function checkUserHome() {
    if(!userHome || !pathExists(userHome)) {
        throw new Error(colors.red('当前登录用户主目录不存在'));
    }
}

/**
 *  root 降级
 *  防止当前用户的权限导致影响文件的读写, root 降级处理 
 */
function checkRoot() {
    const rootCheck = require('root-check');
    rootCheck();
}

function checkNodeVersion() {
    // 获取当前node版本号
    const currentVersion = process.version; 
    if(semver.lt(currentVersion, LOWEST_NODE_VERSION)) {
        throw new Error(colors.red(`mzy-cli-dev 的版本应该大于v${LOWEST_NODE_VERSION}版本的node.js, 当前版本为${currentVersion}`))
    }else{
        log.success("cli", "Node版本号正常")
    }
}


function checkVersion() {
    console.log(pkg.version);
    log.success("cli", "Package版本号正常")
}